<template>
    <div class="documentIndex">
        <bread :title="title" :desc="desc"></bread>
        <div class="content-img">
            <el-upload
                ref="upload"
                class="upload-img"
                multiple
                accept=".jpg,.jpeg,.png"
                :disabled="disableFlag"
                :with-credentials="true"
                :auto-upload="false"
                :file-list="fileList"
                :action="uploadURL"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                :on-exceed="uploadExceed"
                :on-remove="onRemove"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :limit="200"
            >
                <div class="upload">
                    <div class="dragnone">
                        <!-- <div class="box">
                            <el-input
                                v-model="upload"
                                placeholder="将文件拖拽到这里进行上传"
                            ></el-input>
                            <el-button type="primary">本地上传</el-button>
                        </div> -->
                        <div>
                            <span class="tips"
                                >支持文件格式：.jpg .jpeg
                                .png，每次最多上传200张</span
                            >
                        </div>
                        <div class="btn_group">
                            <el-button type="primary">选择文件</el-button>
                            <template v-if="fileList.length > 0">
                                <el-button
                                    type="primary"
                                    @click.prevent="submitUpload"
                                    >确定上传</el-button
                                >
                            </template>
                        </div>
                    </div>
                </div>
            </el-upload>
            <div class="handles">
                <div class="right">
                    <searchFile
                        @on-search="onSearch"
                        @on-clear="onClear"
                    ></searchFile>
                    <el-date-picker
                        style="margin-left:10px; height:32px"
                        v-model="dateValue"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        @change="dateChange"
                        @clear="clearDate"
                    >
                    </el-date-picker>

                    <el-button
                        type="primary"
                        id="batch-download"
                        @click="batchDownload"
                        >批量下载</el-button
                    >
                </div>
            </div>

            <div class="data-table">
                <el-table
                    :data="tableData"
                    ref="multipleTable"
                    tooltip-effect="dark"
                    style="width: 100%"
                    max-height="470"
                    :row-class-name="tableRowClassName"
                    @select="handleSelect"
                    @selection-change="handleSelectionChange"
                    @row-click="handleRowClick"
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading"
                >
                    >
                    <el-table-column type="selection" width="50" align="center">
                    </el-table-column>
                    <el-table-column
                        fixed
                        prop="seqNo"
                        label="文件序号"
                        width="120"
                        align="center"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="resName"
                        label="文件名"
                        width="320"
                        align="left"
                        :show-overflow-tooltip="true"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="size"
                        label="文件大小"
                        width="120"
                        align="center"
                        :formatter="formatSize"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="pageSize"
                        label="页数"
                        width="120"
                        align="center"
                    >
                    </el-table-column>
                    <el-table-column
                        label="处理结果"
                        width="120"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                v-if="scope.row.pageSize > 0"
                                class="processing"
                            >
                                <span>合并完成</span><br />
                                <span
                                    >耗时:{{
                                        formatCost(scope.row.processCost)
                                    }}</span
                                >
                            </div>
                            <div v-else class="processing">
                                <span>正在合并</span>
                                <img src="@assets/images/loading_status.gif" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="uploadUser"
                        label="上传者"
                        align="center"
                        width="150"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="uploadTime"
                        label="上传日期"
                        align="center"
                        width="150"
                    >
                    </el-table-column>
                    <el-table-column
                        label="备注"
                        align="center"
                        width="150"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <div
                                style="cursor: pointer"
                                @click="editRemark(scope.row)"
                            >
                                <i class="el-icon-edit"></i>
                                {{ scope.row.remark }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="150"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                @click="deleteRow(scope.$index, scope.row)"
                                >删除</el-button
                            >
                            <el-button
                                size="mini"
                                @click="downloadRow(scope.$index, scope.row)"
                                >下载</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="page-block">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                >
                </el-pagination>
            </div>
        </div>
        <noteDialog
            :currentItem="currentItem"
            :dialogVisible="noteVisible"
            @on-cancel="noteCancel"
            @on-edit="noteHandle"
        ></noteDialog>
    </div>
</template>

<script>
import searchFile from '@components/common/searchFile.vue'
import noteDialog from '@components/common/noteDialog.vue'
import bread from '@components/common/bread.vue'
import { mapState } from 'vuex'
export default {
  components: {
    searchFile,
    noteDialog,
    bread
  },
  data () {
    return {
      disableFlag: false,
      title: '图片合成PDF',
      desc: '仅支持上传jpe、jpeg、png请上传符合要求的文件',
      tableData: [],
      loading: true,
      total: 0,
      currentPage: this.$api.DEFAULT_PAGE_NUM,
      pageSize: this.$api.DEFAULT_PAGE_SIZE,
      uploadURL: this.$api.UPLOAD_IMG_URL,
      upload: '',
      fileList: [],
      currentItem: {},
      dialogVisible: false,
      noteVisible: false,
      multipleSelection: [],
      selectedId: [],
      dateValue: [],
      searchFile: '',
      fileData: null
    }
  },
  computed: {},
  getters: {},
  mounted () {
    this.getUploadList()
  },
  methods: {
    tableRowClassName ({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return 'even-row'
      }
      return ''
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUploadList(this.searchFile, this.dateValue)
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUploadList(this.searchFile, this.dateValue)
    },
    onSearch (fileName) {
      this.searchFile = fileName
      this.getUploadList(fileName, this.dateValue)
    },
    onClear () {
      this.searchFile = ''
      this.getUploadList(this.searchFile, this.dateValue)
    },
    beforeUpload () {},
    handleChange (file, fileList) {
      const existFile = fileList
        .slice(0, fileList.length - 1)
        .find(f => f.name === file.name)
      if (existFile) {
        console.warn('文件' + file.name + '已经存在!')
        fileList.pop()
      }
      this.fileList = fileList
    },
    uploadExceed (file, filelist) {
      this.$message.err('文件超出个数限制')
    },
    submitUpload () {
      this.disableFlag = true
      // 添加一条假数据
      this.addMockData()
      // 提交
      this.fileData = new FormData()
      for (let i = 0; i < this.fileList.length; i++) {
        this.fileData.append('file', this.fileList[i].raw)
      }
      const url = this.$api.UPLOAD_IMG_URL
      this.$request
        .post(url, this.fileData)
        .then(res => {
          this.uploadSuccess(res)
        })
        .catch(err => {
          console.error(err)
        })
    },
    addMockData () {
      const firstFile = this.fileList[0]
      const firstData = this.tableData[0]
      const mockData = Object.assign({}, firstData)
      const fileName = firstFile.name
      mockData.resName =
                fileName.slice(0, fileName.indexOf('.')) + '.pdf'
      mockData.pageSize = 0
      mockData.size = '--'
      mockData.uploadTime = this.$util.formatTime(new Date())
      this.tableData.unshift(mockData)
    },
    uploadSuccess (res) {
      this.resetUpload()
      this.getUploadList(this.searchFile, this.dateValue)
    },
    resetUpload () {
      this.disableFlag = false
      this.fileList = []
    },
    onRemove (file, fileList) {
      this.fileList = fileList
    },
    uploadError (err, file, fileList) {
      this.resetUpload()
      console.error('upload error', err)
      const res = JSON.parse(err.message)
      if (res.code === '401') {
        this.$router.push('/login')
      }
    },
    getUploadList (fileName, dateArr = []) {
      let url = this.$api.GET_UPLOAD_LIST
      const data = {
        fileName: fileName,
        oprType: 1
      }
      if (dateArr && dateArr.length === 2) {
        (data.beginTime = dateArr[0]), (data.endTime = dateArr[1])
      }
      url = url
        .replace('{pageNum}', this.currentPage)
        .replace('{pageSize}', this.pageSize)
      this.loading = true
      this.$request
        .get(url, data)
        .then(result => {
          this.loading = false
          if (result.code === this.$api.CODE_SUCCESS) {
            this.total = result.data.total
            this.tableData = result.data.list
          }
        })
        .catch(err => {
          this.loading = false
          console.error(err)
        })
    },
    dateChange (dateArr) {
      this.dateValue = dateArr
      this.getUploadList(this.searchFile, dateArr)
    },
    clearDate () {
      this.dateValue = []
      this.getUploadList(this.searchFile, this.dateValue)
    },
    downloadRow (index, tableData) {
      this.selectedId.push(tableData.id)
      const name = tableData.resName
      this.doDownload(name)
    },
    batchDownload () {
      if (this.selectedId.length <= 1) {
        this.$message.warning('请至少勾选两个文件')
      } else {
        this.doDownload()
      }
    },
    doDownload (fileName) {
      const url = this.$api.DOWNLOAD_IMAGE + '?type=pdf'
      if (!fileName) {
        fileName = this.getFileName(this.selectedId[0])
      }
      this.$request
        .download(url, this.selectedId)
        .then(res => {
          const blob = new Blob([res.data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = fileName // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放blob对象
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    getFileName (id) {
      for (let i = 0; i < this.tableData.length; i++) {
        if (id === this.tableData[i].id) {
          const name = this.tableData[i].resName
          return name.slice(0, name.indexOf('.')) + '.zip'
        }
      }
    },
    deleteRow (index, tableData) {
      const id = tableData.id
      const url = this.$api.DEL_DATA.replace('{id}', id)
      this.$request.get(url).then(res => {
        this.$message.success('删除成功')
        this.getUploadList()
      })
    },
    editRemark (item) {
      this.currentItem = item
      this.noteVisible = true
    },
    noteCancel () {
      this.noteVisible = false
    },
    noteHandle (text) {
      this.noteVisible = false
      let url = this.$api.UPDATE_REMARK
      const id = this.currentItem.id
      url = url.replace('{id}', id)
      const data = {
        remark: text
      }
      this.$request
        .get(url, data)
        .then(res => {
          this.$message.success('修改成功')
          this.getUploadList()
        })
        .catch(e => {
          console.log(e)
        })
    },
    formatSize (row, column) {
      return this.$util.formatValue(row.size)
    },
    handleSelect (rows) {},
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.getSelectId()
    },
    // 点击行触发，选中或不选中复选框
    handleRowClick (row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    getSelectId () {
      this.selectedId = []
      this.multipleSelection.forEach(row => {
        this.selectedId.push(row.id)
      })
    },
    formatCost (val) {
      if (val === 0) {
        val = '0_0秒'
      }
      return this.$util.formatValue(val)
    }
  }
}
</script>

<style lang="stylus">
@import './img2pdf.styl'
.el-table
    .even-row
        background #fafafa

.processing
    height 50px
    text-align center
    display block
    span
        font-size 9pt
        font-weight 10
    img
        width 100px
        height 38px
        margin-top -5px

.el-table td {
    padding: 8px 0;
}

#batch-download
    margin-left: 20px
    margin-right 8px
    border-radius: 4px;
    background: #16336c;
    border-color: #16336c;
    color: #fff;
    height: 32px;
    text-align: center;
</style>
